<?php

namespace App\Service;

use App\Models\EwCats;

class CatsService extends BaseService
{
	public static function getList($params, $count = FALSE)
	{
		$query = EwCats::query();
		$query->columns(['id,name,group_id']);

		//group_id
		if (isset($params->group_id) && $params->group_id > 0)
			$query->andwhere("group_id = :group_id:")->bind(['group_id' => $params->group_id]);

		//name
		if (isset($params->name) && $params->name ){
			$query->andwhere("name LIKE '%" . $params->name . "%'");
		}

		//总条数
		if ($count)
			return $query->execute()->count();

		$sql = " order_by DESC, id ASC";

		//order_by 排序
		if (isset($params->order_by))
			$sql = parent::orderBy($params->order_by);

		$query->orderBy($sql);

		//分页
		$query->limit($params->page_num,($params->p-1)*$params->page_num);

		return $query->execute();
	}

	public static function getInfo($id = 0)
	{
		return EwCats::findFirst($id);
	}

	public static function count($params = NULL)
	{
		if (isset($params->group_id) && $params->group_id){
			return EwCats::count([
					"group_id = :group_id:",
					"bind" => [
						"group_id" => $params->group_id,
					],
				]);
		}

		return EwCats::count();
	}

	/**
	 * [getTableCats 获取table对应的分类]
	 * @param  [type] $group_id [1house 2news]
	 * @return [type]           [description]
	 */
	public static function getTableCats($group_id = null)
	{
		if (!intval($group_id)>0)
			return NULL;
		return EwCats::query()->columns(['id'])->addWhere("group_id = " . $group_id)->orderBy("order_by DESC, id ASC")->execute()->toArray();
	}

	/**
	 * [save 保存数据]
	 * @param  [type] $data [description]
	 * @return [type]       [description]
	 */
	public static function save($data)
	{
		$row = new EwCats;
		if (isset($data->id) && $data->id)
			$row = EwCats::findFirst($data->id);

		return $row->save((array)$data);
	}

	/**
	 * [delete 彻底删除]
	 * @param  [type] $id [description]
	 * @return [type]     [description]
	 */
	public static function forever($id)
	{
		if (isset($id) && $id)
			$row = EwCats::findFirst($id);

		if ($row)
			return $row->delete();

		return NULL;
	}
}